/**
 * 
 */
package zj.sweepmine.model;

import java.util.Random;

/**
 * @author Administrator
 * 
 */
public class SweepMine {
	final static int MINE = 9;
	final static int EMPTY = 0;
	static Random r = new Random();
	int row;
	int col;
	int mines;
	int M[][];
	boolean visited[][];

	public SweepMine(int row, int col, int mines) {
		this.row = row;
		this.col = col;
		this.mines = mines;
		M = new int[row][col];
		visited = new boolean[row][col];
		placeMine();
		updateBoard();
	}

	private void updateBoard() {
		for (int i = 0; i < row; i++)
			for (int j = 0; j < col; j++) {
				if (M[i][j] != MINE)
					M[i][j] = count8(i, j);
			}

	}

	private int count8(int x, int y) {
		int result = 0;
		for (int i = x - 1; i <= x + 1; i++)
			for (int j = y - 1; j <= y + 1; j++) {
				if (!checkPos(i, j)|| i == x && j == y)
					continue;
				if (M[i][j] == MINE)
					++result;
			}
		return result;
	}

	private boolean checkPos(int i, int j) {

		return i >= 0 && i < row && j >= 0 && j < col;
	}

	private void placeMine() {
		for (int placed = 0; placed < mines;) {
			int x = r.nextInt(row);
			int y = r.nextInt(col);
			if (M[x][y] != MINE) {
				M[x][y] = MINE;
				++placed;
			}

		}

	}

	public void disp() {
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				System.out.print(M[i][j]);
			}
			System.out.println();
		}

	}

}
